package com.apes.fn.server.InnerError;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanDao;
import com.apes.fn.server.servicePlan.repository.ServicePlanItemRepository;
import com.apes.fn.server.servicePlan.service.ServiceToForeign;
import com.apes.fn.server.workOrder.model.MaintenanceOrder;
import com.apes.fn.server.workOrder.repository.MaintenanceOrderRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.plugin.mq.annotation.Consumer;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Creator: zouyc
 * CreateDate: 2020-11-25 15:17
 * Description:
 **/
@Service("innerErrorDealService")
public class InnerErrorDealService extends DomainService {
    @Autowired
    InnerErrorRepository innerErrorRepository;
    @Autowired
    ServicePlanItemRepository servicePlanItemRepository;
    @Autowired
    MaintenanceOrderRepository maintenanceOrderRepository;
    @Autowired
    ServiceToForeign serviceToForeign;
    @Autowired
    ServicePlanDao servicePlanDao;
    public void errorDeal(SimpleRequest re){
        Date date = re.getJO().getDate("CLRQ");
        JSONObject json1 = new JSONObject();
        json1.put("CLRQ",date);
        List list = servicePlanDao.queryInnerError(json1);
        list.forEach(listTemp -> {
            JSONObject json = (JSONObject)listTemp;
            MQUtil.publish("inner.error.price", "内协错误", MapUtil.mapper("id",json.getString("ID")));
        });
    }

    @Consumer(topic = "inner.error.price")
    public void recordInnerError(SimpleRequest re){
        JSONObject jo = re.getJO();
        ServicePlanItem servicePlanItem = servicePlanItemRepository.findOne(jo.getString("id"));

        InnerError innerError = innerErrorRepository.findOne(servicePlanItem.getId());
        innerError = innerError == null ? new InnerError() : innerError;
        innerError.setId(servicePlanItem.getId());
        innerError.setProduct(servicePlanItem.getProduct().getId());
        innerError.setReferTaxOld(servicePlanItem.getReferTax());

        ServicePlan servicePlan = servicePlanItem.getServicePlan();
        Dept innerDept = new Dept();
        if(servicePlanItem.getOldFrameSourceFrom() != null && servicePlan.getBelongDept().getId() != servicePlan.getServiceDept().getId()){ //老框架，整单内协
            innerDept = servicePlan.getServiceDept();
        }else{
            List list = new ArrayList( );
            list.add(servicePlanItem.getId());
            List<MaintenanceOrder> maintenanceOrders = maintenanceOrderRepository.findCommonMaintenanceOrder(list);

            if(maintenanceOrders.size() == 0){
                innerError.setReferTaxNew( 0);
                innerError.setModelPrice(0);
                innerErrorRepository.saveAndFlush(innerError);
                return;
            }
            innerDept = maintenanceOrders.stream().findFirst().get().getInnerDept();
        }

        JSONObject priceJson = serviceToForeign.getGS51(MapUtil.mapper(
                "SPID",servicePlanItem.getProduct().getId(),
                "PLID",servicePlanItem.getProduct().getClassify().getId(),
                "PZID",servicePlanItem.getProduct().getBrand().getQuality() == null ? null : servicePlanItem.getProduct().getBrand().getQuality().getCode(),
                "CGZZID",servicePlanItem.getPlatform().getId(),
                "JLDW",servicePlanItem.getUom().getName(),
                "SYGSID",servicePlanItem.getPlatform().getId(),
                "CLFWDJID",((CarServiceLevel)(SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(servicePlan.getFnCustomerExpand().getJekunModelCode()))).getId(),
                "JCGSID",servicePlan.getCompany().getId(),
                "JLDWID",servicePlanItem.getUom().getId(),
                "JRS",servicePlan.getCustomerCar().get("vendorCode"),

                "GSID",innerDept.getCompany().getId(),
                "YYMS",innerDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "NYYMS",innerDept.getCompany().getParty().getCorporate().getOperation().getId(),
                "KHID", SpringManager.getBean(PartyRoleService.class)
                        .findByPartyAndRole(innerDept.getCompany().getParty().getId(), "Customer").getId()
        ));

        innerError.setReferTaxNew(priceJson.getDoubleValue("pftPriceUnit"));
        innerError.setModelPrice(priceJson.getDoubleValue("modelPrice"));
        innerError.setReferPrice(priceJson.getDoubleValue("referTax"));
        innerError.setRetailPrice(priceJson.getDoubleValue("retailPirce"));

        innerErrorRepository.saveAndFlush(innerError);
    }
}
